import React, { useEffect, useState } from "react";
import { connect } from "react-redux";
import NavHeader from "@/components/NavHeader";
import { Descriptions, Button, Alert, message, Upload } from "antd";
import { LoadingOutlined, UploadOutlined } from "@ant-design/icons";
import actions from "@/store/actions/profile";
import LoginTypes from "@/typings/login-types";
import config from "@/utils/config";
import request from "@/utils/request";
import { getSession } from "@/utils/storage";
import ImgCrop from "antd-img-crop";
// antd-img-crop 样式需要手动导入
import "antd/es/modal/style/index.css";
import "antd/es/slider/style/index.css";

import "./index.less";

const Profile = (props: any) => {
  let [loading, setLoading] = useState(false);
  // 组件加载后直接发起登录验证请求，查看此用户是否已经登录过了，如果没有登录就提示错误
  useEffect(() => {
    props.validate().catch((err: any) => {
      if (getSession("access_token"))
        message.error(err.response ? err.response.data.message : err.message);
    });
  }, []);
  const handleChange = (info: any) => {
    if (info.file.status === "uploading") {
      setLoading(true);
    } else if (info.file.status === "done") {
      let { success, data, message } = info.file.response;
      if (success) {
        setLoading(false);
        props.changeAvatar(data);
      } else {
        message.error(message);
      }
    }
  };

  let content;
  if (props.loginState === LoginTypes.UN_VALIDATE) {
    content = null;
  } else if (props.loginState === LoginTypes.LOGINED) {
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <UploadOutlined />}
        <div className="ant-upload-text">上传</div>
      </div>
    );
    content = (
      <div className="user-info">
        <Descriptions title="当前登录用户">
          <Descriptions.Item label="用户名">
            {props.user.username}
          </Descriptions.Item>
          <Descriptions.Item label="邮箱">{props.user.email}</Descriptions.Item>
          <Descriptions.Item label="头像">
            <ImgCrop>
              <Upload
                name="avatar"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action={config.base + "/api/user/uploadAvatar"}
                headers={{
                  authorization: request.getToken(),
                }}
                beforeUpload={beforeUpload}
                onChange={handleChange}
                transformFile={(file) => file}
              >
                {props.user.avatar ? (
                  <img
                    src={props.user.avatar}
                    alt="avatar"
                    className="avatar"
                  ></img>
                ) : (
                  uploadButton
                )}
              </Upload>
            </ImgCrop>
          </Descriptions.Item>
        </Descriptions>
        <Button type="primary" onClick={props.logout}>
          退出登录
        </Button>
      </div>
    );
  } else {
    //如果没有登录,则显示注册和登录按钮
    content = (
      <>
        <Alert
          type="warning"
          message="当前未登录"
          description="当前未登录,请选择注册或登录"
        ></Alert>
        <div style={{ textAlign: "center", padding: "50px" }}>
          <Button
            type="dashed"
            onClick={() => {
              props.history.push("/login");
            }}
          >
            登录
          </Button>
          <Button
            type="dashed"
            style={{ marginLeft: "50px" }}
            onClick={() => {
              props.history.push("/register");
            }}
          >
            注册
          </Button>
        </div>
      </>
    );
  }
  return (
    <div>
      <NavHeader history={props.history}>个人中心</NavHeader>
      {content}
    </div>
  );
};

function beforeUpload(file: any): boolean {
  const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJpgOrPng) {
    message.error("你只能上传jpg/png文件!");
  }
  const isLessThan2M = file.size / 1024 / 1024 < 2;
  if (!isLessThan2M) {
    message.error("图片必须小于2MB");
  }
  return isJpgOrPng && isLessThan2M;
}

let mapStateToProps = (state: any): any => state.profile;
export default connect(mapStateToProps, actions)(Profile);
